package com.leyou.gateway.filters;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 虎哥
 */
@Order(0)
@Component
public class LoginFilter implements GlobalFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取cookie中的jti
        // 1.1.获取request
        ServerHttpRequest request = exchange.getRequest();
        // 1.2.获取所有cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        // 1.3.根据名称获取指定cookie
        HttpCookie cookie = cookies.getFirst(JwtConstants.COOKIE_NAME);
        // 1.4.判断
        if(cookie == null){
            // 放行
            return chain.filter(exchange);
        }
        // 1.5.获取jwt
        String jwt = cookie.getValue();
        // 2.刷新有效期
        jwtUtils.refreshJwt(jwt);
        // 3.放行
        return chain.filter(exchange);
    }
}
